package com.ciaojian.client.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ciaojian.client.service.CouponCodeServiceImpl;
import com.ciaojian.client.service.ExchangeServiceImpl;
import com.ciaojian.client.service.MemberDetailServiceImpl;
import com.ciaojian.client.service.UserServiceImpl;
import com.ciaojian.core.base.annotation.ApiIdempotent;
import com.ciaojian.core.exception.EntityNotFoundException;
import com.ciaojian.core.mapper.PhoneCreditMapper;
import com.ciaojian.core.model.*;
import com.ciaojian.core.service.PhoneCreditService;
import com.ciaojian.core.util.Result;
import io.swagger.annotations.*;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.Optional;

/**
 * @author Atlakyn
 */
@Api(tags = {"权益模块: 会员权益"})
@Validated
@RestController
@RequestMapping("/member-detail")
public class MemberDetailController {
    @Resource
    private UserServiceImpl userService;
    @Resource
    private MemberDetailServiceImpl memberDetailService;
    @Resource
    private ExchangeServiceImpl exchangeService;
    @Resource
    private PhoneCreditService<PhoneCreditMapper, PhoneCredit> phoneCreditService;
    @Resource
    private CouponCodeServiceImpl couponCodeService;

    @ApiOperation("获取会员权益列表")
    @ApiResponses({@ApiResponse(code = 200, message = "success", response = MemberDetail.class)})
    @GetMapping

    public Result getMemberDetailAndBoughtCount(Integer userId) {
        Assert.notNull(userId, "用户id不能为空");
        return Result.ok(memberDetailService.getBaseMapper().getMemberDetailAndBoughtCount(userId));
    }

    @ApiOperation("获取用户已购买的权益")
    @ApiResponses({@ApiResponse(code = 200, message = "success", response = MemberDetail.class)})
    @GetMapping("/user-bought")
    public Result getUserBought(Integer userId) {
        Assert.notNull(userId, "用户 Id 不能为空");
        return Result.ok(memberDetailService.getBaseMapper().getUserBought(userId));
    }

    @ApiOperation("查询用户权益详情")
    @GetMapping("/user-own")
    public Result getMemberDetailUserOwn(@NotNull(message = "请选择权益订单") Integer orderId) {
        Order order = new Order().selectById(orderId);
        Assert.notNull(order, "权益订单不存在!");
        return Result.ok(couponCodeService.getMemberDetailUserOwn(orderId));
    }

    @ApiOperation("获取权益信息")
    @ApiResponses({@ApiResponse(code = 200, message = "success", response = MemberDetail.class)})
    @GetMapping("/{memberDetailId}")
    public Result getMemberDetail(@PathVariable Integer memberDetailId) {
        return Result.ok(new MemberDetail().selectById(memberDetailId));
    }

    @ApiOperation("权益兑换")
    @ApiIdempotent
    @PostMapping("/exchange")
    public Result exchange(@NotNull(message = "userId must not be null") Integer userId,
                           @NotBlank(message = "请输入券码") String code) {
        User user = Optional.ofNullable(userService.getById(userId))
                .orElseThrow(() -> new EntityNotFoundException(User.class, "id", userId));

        Exchange exchange = Optional.ofNullable(exchangeService.getBaseMapper().getByCode(code))
                .orElseThrow(() -> new EntityNotFoundException("您的兑换码错误"));

        Assert.isTrue(exchange.getStatus() == 0, "此码已失效");
        Assert.isTrue(exchange.getExpiredTime().after(new Date()), "此码已失效");

        return Result.save(exchangeService.exchange(user, exchange));
    }

    @ApiOperation("查询话费权益绑定记录")
    @GetMapping("/credit-record")
    public Result creditRecord(@NotNull(message = "code must be not null!") String code) {
        PhoneCredit one = phoneCreditService.lambdaQuery()
                .eq(PhoneCredit::getCode, code)
                .one();
        return Result.ok(one);
    }


    @ApiOperation("权益会员套餐列表")
    @GetMapping("/combines/{combinesId}/{member}")
    public Result getCombines(@PathVariable int combinesId,
                              @PathVariable  @ApiParam("可见状态(已完成已支付的订单) 0全部可见 1仅老用户可见 2仅新用户可见") int member) {

        return Result.ok(memberDetailService.getMemberDetailList(combinesId,member));
    }


    @ApiOperation("话费充值权益-输入手机号")
    @PostMapping("/fill-phone")
    public Result fillRechargePhone(@Validated @RequestBody PhoneCredit phoneCredit) {
        // 判断券码是否已经使用过
        boolean flag = phoneCreditService.lambdaQuery()
                .eq(PhoneCredit::getCode, phoneCredit.getCode())
                .count() == 0;
        Assert.isTrue(flag, "此券已使用");
        return Result.save(phoneCredit.insert());
    }

    @ApiOperation("查询积分商城详情")
    @GetMapping("/shoppingOrderInfo")
    public Result shoppingOrderInfo(@NotNull(message = "请选择积分商城订单") Integer orderId) {


        return Result.ok(couponCodeService.shoppingOrderInfo(orderId));
    }
}